'use strict';

const Controller = require('../base.js');
const SELECT = require('../../../../config/select');
class CommentChildrenController extends Controller {
	/**
     *子评论获取
     */
	async find() {
		const { ctx } = this;
		const { commentId, page, currentPage } = ctx.query;

		const Rules = {
			commentId: {
				type: 'string',
				keyname: '父评论ID'
			}
		};
		ctx.proving(Rules, ctx.query);

		const select = SELECT.COMMENT_CHILDREN;
		const res = await ctx.service.commentChildren.find({ commentId, page, currentPage }, select);
		ctx.success(res);
	}

	/**
     * 新增子评论
     */
	async create() {
		const { ctx, app } = this;
		const body = ctx.request.body;
		const articleId = body.articleId;
		const commentId = body.commentId;
		let content = body.content;

		const Rules = {
			articleId: {
				type: 'objectId',
				keyname: '文章ID'
			},
			commentId: {
				type: 'objectId',
				keyname: '父评论ID'
			},
			content: {
				type: 'string',
				keyname: '评论内容'
			}
		};
		ctx.proving(Rules);
		// 取出被@的用户
		let sendees = app.fetchUsers(content);
		// 将文章内容中被@的用户进行格式化
		content = app.linkUsers(content);
		// 写入数据库
		const comment = await ctx.service.commentChildren.create({
			articleId,
			commentId,
			content
		});

		// 通知被@的用户
		ctx.service.article.find({ id: articleId }).then((res) => {
			console.log('评论时获取到的文章信息：', res);
			// 给被@的用户发消息
			this.submitMsg({
				sendees,
				content: `用户<a href="#/user/${ctx.state.user._id}">${ctx.state.user
					.name}</a>在文章<a href="#/article/${articleId}">${res.title}</a>的评论中提到了你`,
				type: 0
			});
			// 给评论作者发消息
			this.submitMsg({
				sendees: [ comment.auth ],
				content: `用户<a href="#/user/${ctx.state.user._id}">${ctx.state.user.name}</a>评论了您在文章<a href="#/article/${articleId}">${res.title}</a>的评论`,
				type: 0
			});
		});
		ctx.success({ id: comment.id });
	}

	/*
     * 删除评论
     * */
	async destroy() {
		const { ctx } = this;
		const body = ctx.request.body;
		const id = body.id;

		const Rules = {
			id: {
				type: 'objectId',
				keyname: '子评论ID'
			}
		};
		ctx.proving(Rules);

		const article = await ctx.service.commentChildren.destroy(id);

		ctx.success({
			message: '删除成功'
		});
	}

	/*
     * 点赞，取消点赞
     * */
	async likeComment() {
		const { ctx } = this;
		const body = ctx.request.body;
		const id = body.id;
		const Rules = {
			id: {
				type: 'objectId',
				keyname: '子评论ID'
			}
		};
		ctx.proving(Rules);
		const res = await ctx.service.commentChildren.userLikeComment(id);
		ctx.success(res);
	}
}

module.exports = CommentChildrenController;
